package com.zlp.netty.lecture;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: zhulaiping
 * @time: 2022/9/6 11:42
 */
@Slf4j
public class EchoSever {

    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup(1),new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder());

                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                log.debug("收到客户端发来信息：{}",msg);
                                //ctx.fireChannelRead(msg);
                                //向channel中写入数据传递给客户端，若是channel调用，就直接从tail处开始向前查询出战处理器
                                ch.writeAndFlush(ctx.alloc().buffer().writeBytes(msg.getBytes()));
                            }
                        });
                    }
                }).bind(8080);
    }
}
